//
//  UserAdressViewController.m
//  danpin
//
//  Created by chuangjia on 26/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "UserAdressViewController.h"
#import "UserAddressEditViewController.h"
#import "UserAddressCell.h"
#import "BaseModel.h"

@interface UserAdressViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,strong)NSDictionary *addressDict;
@property(nonatomic,strong)void(^actionBlock)(id,id);
@end

@implementation UserAdressViewController
@synthesize tbView=_tbView;
@synthesize sectionArray=_sectionArray;
@synthesize type=_type;
@synthesize addressDict=_addressDict;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"地址管理";
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    [self initUI];
    [self notificationManager];
    [self getAddressList];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
 
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //todo , 时机其实不对，应该在用户返回的时候调用。
    [self selectDefaultAddress];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if(_sectionArray)
    {
        [_sectionArray removeAllObjects];
        _sectionArray = nil;
    }
    self.tbView = nil;
    self.actionBlock=nil;
    self.addressDict=nil;
}
-(void)setSelectedCallBack:(void(^)(id,id))callback
{
    self.actionBlock=callback;
}
-(void)notificationManager
{
  
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateLoveList:)
                                                 name:@"updateAddressList"
                                               object:nil];
    
    
    
}
-(void)updateLoveList:(NSNotification*)notification
{
   [self getAddressList];
}

-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)-50) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =UIColorFromRGB(0xf8f8f8);
    _tbView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    
    UIView *bottom = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-50, self.view.frame.size.width, 50)];
    bottom.backgroundColor =[UIColor clearColor];
    UIButton *addBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(PHOTO_FRAME_WIDTH*2, 5, self.view.frame.size.width - PHOTO_FRAME_WIDTH*4, 40);
    addBtn.backgroundColor=UIColorFromRGB(0xDE3B30);
    [addBtn setTitle:@"+添加新地址" forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addressAction) forControlEvents:UIControlEventTouchUpInside];
    [bottom addSubview:addBtn];
    
    [self.view addSubview:bottom];
    bottom=nil;
}


- (void) selectDefaultAddress
{
    
    //用户返回时，自动帮助用户选择一个默认地址。
    if (_sectionArray.count != 1) {
        return;
    }
    
    NSDictionary *dict =[self.sectionArray objectAtIndex:0];
    if (self.actionBlock)
    {
        self.actionBlock(dict,@"brand");
    }
   
}


#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_sectionArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UserAddressCell returnCellHeight:nil];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserAddressCell *cell = (UserAddressCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    if(cell == nil)
    {
        cell = [[UserAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    if (indexPath.section>=_sectionArray.count) {
        return cell;
    }
    NSDictionary *dict = [_sectionArray objectAtIndex:indexPath.section];
    [cell showInfo:dict key:@"UserAddressCell" indexPath:indexPath];
    return cell;
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_addressdefault:
        {
                NSString *pid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"id"]];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:pid forKey:@"id"];
                __weak typeof (self) wSelf = self;
                [BaseModel setDefaultShopAddress:dict success:^(AFHTTPRequestOperation *operation, id result) {
                    if (result&&[result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultDist =(NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                        [wSelf getAddressList];
                    }
                } failure:^(NSError *error) {
                    [[ZToastManager ShardInstance] showtoast:@"设置失败"];
                }];
            
        }
            break;
        case BEventType_addressedit:
        {
            UserAddressEditViewController *edit = [[UserAddressEditViewController alloc] init];
            edit.type=1;
            edit.addressDictionary = obj;
            [self.navigationController pushViewController:edit animated:YES];
            edit=nil;
        }
            break;
        case BEventType_addressdelete:
        {
            self.addressDict = obj;
            NSString *pid =[NSString stringWithFormat:@"是否删除\"%@\"这个地址?",[obj objectForKey:@"detail_address"]];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:pid delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
            
        }
            break;
        default:
            break;
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            
            NSString *pid =[NSString stringWithFormat:@"%@",[self.addressDict objectForKey:@"id"]];
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:pid forKey:@"id"];
            [BaseModel delShopAddressById:dict success:^(AFHTTPRequestOperation *operation, id result) {
                if (result&&[result isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *resultDist =(NSDictionary*)result;
                    [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                    for(int i=0;i<[_sectionArray count];i++)
                    {
                        NSDictionary *dict = [_sectionArray objectAtIndex:i];
                        NSString *ids =[dict objectForKey:@"id"];
                        if ([ids isEqualToString:pid]) {
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteAddressList" object:nil];
                            [_sectionArray removeObject:dict];
                            break;
                        }
                    }
                    [_tbView reloadData];
                }
            } failure:^(NSError *error) {
                [[ZToastManager ShardInstance] showtoast:@"删除失败"];
            }];
        }
            break;
        default:
            break;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_type == 1)
    {
        if (indexPath.section>=_sectionArray.count) {
            return;
        }
        NSDictionary *dict =[self.sectionArray objectAtIndex:indexPath.section];
        if (self.actionBlock) {
            self.actionBlock(dict,@"brand");
        }
        [self.navigationController popViewControllerAnimated:YES];
        
        
    }
    
}
#pragma method editaction
-(void)addressAction
{
    UserAddressEditViewController *edit = [[UserAddressEditViewController alloc] init];
    edit.type=0;
    if (_sectionArray.count>0) {
         edit.is_Default = @"0";
    }else{
         edit.is_Default = @"1";
    }
    
    [self.navigationController pushViewController:edit animated:YES];
    edit=nil;
}
-(void)getAddressList
{
    [ZShare showAnimationView:self.view center:CGPointZero];
    __weak typeof (self) wSelf = self;
    [BaseModel getShopAddressList:nil success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
          [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
          [ZShare hiddenAnimationView:wSelf.view];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    [ZShare hiddenAnimationView:self.view];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        if (resultObject && [[resultObject allKeys] containsObject:@"ipAddress"]) {
            id ipAddress = [resultObject objectForKey:@"ipAddress"];
            if (ipAddress && [ipAddress isKindOfClass:[NSDictionary class]]) {
                [ZShare sharedInstance].ipAddress = ipAddress;
            }
        }
      
        id data =  [resultObject objectForKey:@"list"];
        if (data && [data isKindOfClass:[NSArray class]]){
            if (!_sectionArray) {
                _sectionArray =[[NSMutableArray alloc] init];
            }
            [_sectionArray removeAllObjects];
            [_sectionArray addObjectsFromArray:data];
            self.tbView.tableFooterView =nil;
        }else{
            if (_sectionArray.count==0)
            {
                self.tbView.tableFooterView =[self footerView:@"您还没有收货地址" buttonText:@"添加新地址"];
                
              //  if(strBtnText)
                {
                    
                    UIButton* btnAddAddress = [UIButton buttonWithType:UIButtonTypeCustom];
                    btnAddAddress.backgroundColor = [UIColor clearColor];
                    [btnAddAddress setTitleColor:RED_COLOR forState:UIControlStateNormal];
                    btnAddAddress.titleLabel.font = FONT(13);
                    [btnAddAddress setTitle:@"点此添加新地址" forState:UIControlStateNormal];
                    btnAddAddress.frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 30);
                    
                    [btnAddAddress addTarget:self action:@selector(addressAction) forControlEvents:UIControlEventTouchUpInside];
                    
                    
                    [self.tbView.tableFooterView addSubview:btnAddAddress];
                }
                
            }
        }
        BOOL isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        
        if (isLoadFinished) {
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[self footerView:end_msg buttonText:nil];
        }
    }
    [self.tbView reloadData];
}
@end
